package com.atguigu.tingshu.user.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONString;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.common.util.RandomUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.AlbumStatMqVo;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public BigDecimal getTrackBreakSecond(Long userId, Long trackId) {

        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);

        Query query = new Query();
        query.addCriteria(Criteria.where("trackId").is(trackId).and("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC, "updateTime"));
        query.limit(1);

        UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        if (listenProcess != null) {
            return listenProcess.getBreakSecond();
        }
        return new BigDecimal(0);
    }

    @Override
    public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) {

        Long trackId = userListenProcessVo.getTrackId();
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        Query query = new Query();
        query.addCriteria(Criteria.where("trackId").is(trackId).and("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC, "updateTime"));
        query.limit(1);

        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        if (userListenProcess != null) {
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setUpdateTime(new Date());
        } else {
            userListenProcess = new UserListenProcess();
            userListenProcess.setUserId(userId);
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setTrackId(userListenProcessVo.getTrackId());
            userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
            userListenProcess.setCreateTime(new Date());
            userListenProcess.setUpdateTime(new Date());
            userListenProcess.setIsShow(1);
        }
        mongoTemplate.save(userListenProcess, collectionName);

        String lockKey = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX + userId + ":" + trackId;
        String lockValue = userId + ":" + trackId;
        Long ttl = DateUtil.endOfDay(new Date()).getTime() - System.currentTimeMillis();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, ttl, TimeUnit.MILLISECONDS);
        if (flag) {
            TrackStatMqVo trackStatMqVo = new TrackStatMqVo();

            trackStatMqVo.setBusinessNo(IdUtil.fastSimpleUUID());
            trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            trackStatMqVo.setCount(1);
            trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
            trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());

            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK, MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
        }

    }

    @Override
    public Map<String, Long> getLatelyTrack(Long userId) {

        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC,"updateTime"));
        query.limit(1);

        HashMap<String, Long> resultMap = new HashMap<>();
        //设置默认值
        resultMap.put("trackId",1606L);
        resultMap.put("albumId",51948L);

        UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class,collectionName);
        if (listenProcess!=null){

            resultMap.put("trackId",listenProcess.getTrackId());
            resultMap.put("albumId",listenProcess.getAlbumId());

        }

        return resultMap;
    }
}
